<?php

namespace App\Service;

use App\Enums\BaseErrorCode;
use App\Exceptions\Custom\ResponseHttpException;
use Illuminate\Contracts\Pagination\LengthAwarePaginator;

class BaseService
{
    /**
     * 通用返回
     *
     * @param int $code 200 正常
     * @param string $msg
     * @param array|null $data
     * @return array
     */
    public static function returnData(int $code, string $msg = '', array $data = null): array
    {
        return ['code' => $code, 'msg' => $msg, 'data' => $data ?: null];
    }

    /**
     * 标准分页返回
     * @param LengthAwarePaginator $paginator
     * @param \Closure $closure
     * @return array
     */
    public static function pageLists(LengthAwarePaginator $paginator, \Closure $closure): array
    {
        return [
            'list'     => collect($paginator->items())->map($closure)->filter()->values(),
            'pageNum'  => $paginator->currentPage(),
            'pageSize' => $paginator->perPage(),
            'count'    => $paginator->total(),
        ];
    }

    /**
     * 通用报错返回
     * @param string $msg
     * @param int|null $errCode
     * @return mixed
     */
    public static function throwErr(string $msg, ?int $errCode = null): void
    {
        if ($errCode === null) {
            $errCode = BaseErrorCode::$ERROR_OCCURRED;
        }

        throw new ResponseHttpException($errCode, null, $msg);
    }

    /**
     * 格式化百分比
     * @param numeric $changeNum 变量
     * @param numeric $oriNum 原量
     * @return float
     */
    public static function formatPercent($changeNum, $oriNum): float
    {
        if ($changeNum == 0 || $oriNum == 0) {
            return 0;
        }

        return (float)bcmul(bcdiv($changeNum, $oriNum, 4), 100, 2);
    }
}
